import os
import sys
import hashlib
from optparse import OptionParser


md5_2_file = {}


def md5_file(file_name):
    md5file = open(file_name, 'rb')

    md5 = hashlib.md5(md5file.read()).hexdigest().upper()

    md5file.close()

    global md5_2_file

    if md5 not in md5_2_file:
        md5_2_file.update({md5: True})
    else:
        os.remove(file_name)


def detect_dir(target_dir):
    for root, dirs, files in os.walk(target_dir):
        for file_x in files:
            md5_file(os.path.join(root, file_x))
        if not is_nest:
            return
        for dir_x in dirs:
            detect_dir(os.path.join(root, dir_x))


def add_option():
    parser.add_option("-d", "--dir", dest="target_dir", default=None, help="target dir")
    parser.add_option("-i", "--is_nest", dest="is_nest", default=False, help="nest")


def check_param(target_dir):
    if target_dir is None or not os.path.isdir(target_dir):
        print "dir invalid"
        parser.print_help()
        sys.exit(1)


if __name__ == '__main__':
    parser = OptionParser()
    add_option()
    (options, args) = parser.parse_args()
    t_dir = options.target_dir
    is_nest = options.is_nest
    check_param(t_dir)

    print "run with:", (t_dir)
    detect_dir(t_dir)
    a = dict()
    a = {}
    print "end."
